<script setup>
// 展示场景
import {computed, getCurrentInstance, inject, reactive, ref} from "vue";
import {crmSceneSaveAPI, filterIndexfieldsAPI, filterIndexPoolfieldsAPI} from "@/api/crm/common.js";
import crmTypeModel from "@/views/crm/model/crmTypeModel.js";
import {
  crmOptionKey,
  tableHeadSortDataKey
} from "/src/views/crm/componentsNew/SzCrud/keys";

import {sceneDataKey} from "../keys.js";
import SceneList from "@/views/scrm/component/search/MySceneList.vue";
import ManageScene from "@/views/scrm/component/search/MyManageScene.vue";
import CreateScene from "@/views/scrm/component/search/MyCreateScene.vue";
import FilterForm from "/src/views/crm/componentsNew/FilterFormNew/index.vue";
import FilterContent from "/src/views/crm/componentsNew/FilterFormNew/FilterContent.vue";


const filterObj = reactive({form: []}) // 筛选确定数据
const fieldList = ref([])
const showFilter = ref(false) // 控制筛选框
const showScene = ref(false) // 场景操作
const showSceneManage = ref(false) // 展示场景设置
const showSceneCreate = ref(false) // 展示场景添加
const sceneFilterObj = reactive({form: []}) // 筛选确定数据

const emits = defineEmits(['scene', 'filter', 'handle'])

const iconClass = computed(() => {
  return showScene.value ? 'arrow-up' : 'arrow-down'
})

const sortData = inject(tableHeadSortDataKey)
const crmOption = inject(crmOptionKey)


const sceneData = inject(sceneDataKey)

// 场景操作
/** 选择了场景 */
function sceneSelect(data) {
  sceneData.id = data.id
  sceneData.name = data.name
  sceneData.bydata = data.bydata
  emits('scene', data)
}


function handleFilter(form) {
  console.log("handleFilter", form)
  filterObj.value = form
  showFilter.value = false
  if (form.saveChecked) {
    crmSceneSaveAPI({
      type: crmTypeModel[crmOption.crmType],
      isDefault: form.saveDefault ? 1 : 0,
      name: form.saveName,
      data: JSON.stringify(form.obj)
    }).then(res => {
      updateSceneList()
    }).catch(() => {
    })
  }
  emits('filter', form.obj)
}

const refSceneList = ref()

/**  创建保存成功 */
function updateSceneList() {
  // let currentInstance = getCurrentInstance();
  refSceneList.value.getSceneList()
}

// 删除
function handleDeleteField(data) {
  filterObj.value = data.obj
  emits('filter', filterObj.value.obj)
}

const showSceneView = computed(() => {
  if (crmOption.isSeas) {
    return false
  } else {
    return true
  }
})

const sceneName = computed(() => {
  return sceneData.name || '全部'
})

// 展示筛选
const showFilterView = computed(() => {
  if ([].includes(crmOption.crmType)) {
    return false
  } else {
    return true
  }
})

function addScene(data) {
  filterIndexfieldsAPI({label: crmTypeModel[crmOption.crmType]}).then(res => {
    console.log("res", res)
    fieldList.value = res.data.data
    console.log("res", fieldList)
    showSceneCreate.value = true
  }).catch((e) => {
    console.log("res e", e)
  })

}

function manageScene(data) {
  showSceneManage.value = true
}

// 子组件 回调的 结果
function handleCallBack(data) {
  console.log("data", data)
  emits('handle', {type: data.type})
}

/** 展示高级筛选 */
function showFilterClick() {
  getFilterFieldInfo()
}

// 获取高级筛选字段数据
function getFilterFieldInfo() {
  const params = {}
  if (crmOption.isSeas) {
    params.poolId = crmOption.poolId
  } else {
    params.label = crmTypeModel[crmOption.crmType]
  }

  const request = crmOption.isSeas ? filterIndexPoolfieldsAPI : filterIndexfieldsAPI

  request(params).then(res => {
    fieldList.value = res.data.data
    showFilter.value = true
  }).catch(() => {
  })
}
</script>

<template>
  <slot name="custom"/>
  <div v-if="showSceneView">场景：</div>
  <el-popover v-if="showSceneView" v-model:visible="showScene"
              trigger="click" popper-class="no-padding-popover" width="180">
    <template v-slot:reference>
      <el-input v-model="sceneName" :readonly="true" class="scene-select">
        <template v-slot:suffix>
          <el-icon v-if="showScene">
            <ArrowUp/>
          </el-icon>
          <el-icon v-else>
            <ArrowDown/>
          </el-icon>
        </template>
      </el-input>
    </template>
    <SceneList ref="refSceneList" @sceneChange="sceneSelect" @addScene="addScene" @manageScene="manageScene"
               @hideSceneList="showScene=false"/>
  </el-popover>
  <el-button v-if="showFilterView" type="primary" class="filter-button" @click="showFilterClick">
    高级筛选
  </el-button>

  <el-button v-if="sortData && sortData.order && sortData.column"
             type="primary" plain @click="handleCallBack({type: 'clear-sort'})">
    {{
      `${sortData.column.label} ${{ascending: '升序', descending: '降序'}[sortData.order]}` }}
    <i style="margin-left: 5px;" class="el-icon-close"/>
  </el-button>
  <FilterForm v-if="showFilterView" :fieldList="fieldList"
              v-model:dialogVisible="showFilter"
              :obj="filterObj"
              :crm-type="crmOption.crmType"
              :save-scene="!crmOption.isSeas"
              @filter="handleFilter"/>
  <!--默认插槽-->
  <slot name="default"/>

  <template v-if="filterObj.form && filterObj.form.length > 0">
    <FilterContent :obj="filterObj" @delete="handleDeleteField"/>
  </template>
  <ManageScene :dialogVisible="showSceneManage" :crm-type="crmOption.crmType" @save-success="updateSceneList"/>

  <CreateScene :fieldList="fieldList"
               :crmType="crmOption.crmType"
               :dialogVisible="showSceneCreate"
               :obj="sceneFilterObj"
               @save-success="updateSceneList"/>
</template>

<style scoped lang="scss">
.scene-select {
  width: 180px;

  :deep(.el-input__inner) {
    cursor: pointer;
  }
}

.filter-button {
  margin-left: 20px;

  :deep(i) {
    font-size: 14px;
    margin-right: 5px;
  }
}
</style>